<template>
  <div>
    <NavigationBar title-text="登录 / 注册" :custom-back-func="handleNavigateBack" />
    <Message ref="message" />
    <Loading ref="loading" fullscreen />

    <div class="wx-login-container w-full h-screen flex-column pt-200rpx">
      <div class="logo-container w-full flex-column justify-center">
        <div class="image w-full text-center">
          <image
            class="w-230rpx h-230rpx"
            src="/static/images/medical.png"
            mode="aspectFill" />
        </div>
        <div class="w-full mt-10rpx flex-column items-center text-center text-36rpx font-bold text-black">
          <text>医疗服务小程序</text>
        </div>
      </div>
      <div class="login-btn-container w-full">
        <button
          class="wx-login-btn h-90rpx bg-primary text-white text-36rpx"
          @click="handleLoginBtnClick">
          微信一键登录
        </button>
        <!--        <div class="username-login" @click="usernameLogin">-->
        <!--          输入账号登录-->
        <!--        </div>-->
      </div>
      <div class="w-full mt-auto text-center">
        <u-checkbox
          v-model="agreeCheckbox"
          shape="circle"
          :label-disabled="false"
          active-color="#f4756b"
          label-size="28"
          size="36">
          <span>我已阅读并同意</span>
          <span class="ml-10rpx text-primary">
            用户协议及隐私协议
          </span>
        </u-checkbox>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
  import Message from '@/components/message/src/message.vue'
  import type { MessageMethod } from '@/components/message'
  import Loading from '@/components/loading/src/loading.vue'
  import type { LoadingMethod } from '@/components/loading'
  import NavigationBar from '@/components/navigation-bar/src/navigation-bar.vue'
  import {gotoPage} from '@/common/utils'
  import {useUserStore} from '@/store'
  import {userApi} from '@/service/api'
  import {connectSocket} from '@/service/socket'

  const userStore = useUserStore()

  const message = ref<InstanceType<typeof Message> & MessageMethod>(null)
  const loading = ref<InstanceType<typeof Loading> & LoadingMethod>(null)

  const agreeCheckbox = ref<boolean>(false) //用户已阅读并同意使用协议
  const loginSucceeded = ref<boolean>(false) //是否已经登录
  const toUrl = ref<string>('') //登陆成功后要跳转的页面

  /**
   * 微信一键登录
   * @param isNewUser 是否为新用户第一次登录
   */
  const wxLogin = useThrottleFn((isNewUser: boolean): void => {
    if (!agreeCheckbox.value) {
      message.value.warning({
        text: '请阅读并同意用户协议',
        direction: 'top'
      })
      return
    }
    loading.value.startLoading()
    uni.login({
      provider: 'weixin',
      success: ({code}) => {
        userApi.wxLogin({
          code: code
        }).then(async res => {
          //登陆成功
          try {
            const {data: userInfo} = await userApi.getCurrentUserInfo()
            console.log(userInfo);
            
            userInfo && await userStore.setUserInfo(userInfo)
            // setTimeout(() => {
            //   try {
            //     connectSocket()
            //   } catch (e) {
            //     console.error(e)
            //   }
            // }, 0)
            loginSucceeded.value = true
            handleLoginSuccess()
          } catch (e: any) {
            console.error(e)
            message.value.error({
              text: '登陆失败',
              direction: 'top'
            })
          } finally {
            loading.value.stopLoading()
          }
        }).catch(err => {
          if (err.code === 2007) {
            //用户未注册
            wxRegister()
          } else {
            console.error(err)
            loading.value.stopLoading()
            message.value.error({
              text: '登陆失败',
              direction: 'top'
            })
          }
        })
      }
    })
  }, 0, false, false)

  // 为当前微信账号注册
  const wxRegister = (): void => {
    uni.login({
      provider: 'weixin',
      success: ({code}) => {
        userApi.registerByWx({
          code: code
        }).then(() => {
          wxLogin(true)
        }).catch(err => {
          if (err.code === 2008) {
            //账户已存在
            wxLogin(false)
          } else {
            console.error(err)
            loading.value.stopLoading()
            message.value.error({
              text: '注册失败',
              direction: 'top'
            })
          }
        })
      }
    })
  }

  // 获取用户个人资料
  const getUserProfile = (): void => {
    uni.showModal({
      content: '请授权允许获取用户信息',
      confirmText: '立即授权',
      confirmColor: '#f4756b',
      showCancel: false,
      success: ({confirm}) => {
        if (confirm) {
          uni.getUserProfile({
            desc: '请授权获取用户信息',
            lang: 'zh_CN',
            success: res => {
              if (res.errMsg === 'getUserProfile:ok') {
                const encryptedData = res.encryptedData
                const iv = res.iv
                const signature = res.signature
                userApi.bindWxUserInfo({
                  encryptedData: encryptedData,
                  iv: iv
                  // signature: signature
                }).catch(err => {
                  console.error(err)
                }).finally(() => {
                  handleLoginSuccess()
                })
              } else {
                console.error(res)
              }
            }
          })
        }
      }
    })
  }

  // 登录按钮点击事件
  const handleLoginBtnClick = useThrottleFn((): void => {
    if (!loginSucceeded.value) {
      wxLogin(false)
      return
    }
    handleLoginSuccess()
  }, 2000, false, true)

  // 登陆成功
  const handleLoginSuccess = (): void => {
    const navigateOption = {
      url: toUrl.value,
      passedParams: {loginSuccess: true},
      fail: () => gotoPage('/pages/index/index', 'switchTab')
    }
    if (!!toUrl.value) {
      uni.redirectTo(navigateOption)
      return
    }
    uni.navigateBack(navigateOption)
  }

  // 返回上一页
  const handleNavigateBack = (): void => {
    uni.navigateBack({
      delta: 2
    })
  }

  onShow(() => {
    const instance = getCurrentInstance()
    nextTick(() => {
      //@ts-ignore
      toUrl.value = instance?.proxy?.$passedParams?.url ?? ''
    })
  })
</script>

<style scoped lang="scss">
  @import 'login';
</style>
